const path = require('path')
const CompressionPlugin = require('compression-webpack-plugin')

const __PROD__ = process.env.NODE_ENV === 'production'

function resolve(dir) {
  return path.join(__dirname, dir)
}

module.exports = {
  productionSourceMap: false,
  publicPath: __PROD__ ? '/admin/' : '/',
  devServer: {
    open: true,
    port: 9000,
    disableHostCheck: true,
    proxy: {
      '/api': {
        //  target: 'http://192.168.20.18:8099', //一波地址
        target: 'http://47.110.131.107',
        changeOrigin: true, //是否跨域
        pathRewrite: {
          '^/api': '/admin-api',
          //  '^/api': '',
        },
      },
    },
  },
  css: {
    loaderOptions: {
      scss: {
        prependData: `@import "~@/styles/var.scss";
                      @import "~@/styles/mixin.scss";`,
      },
    },
  },
  chainWebpack: config => {
    config.resolve.alias.set('vendor', path.resolve(__dirname, './src/vendor'))
    config.when(__PROD__, config => {
      config.optimization.minimizer('terser').tap(args => {
        args[0].terserOptions.compress['drop_console'] = true
        args[0].terserOptions.compress['drop_debugger'] = true
        return args
      })

      config.optimization.splitChunks({
        chunks: 'all',
        cacheGroups: {
          vendors: {
            chunks: 'initial',
            priority: 10,
            name: 'chunk-libs',
            test: /[\\/]node_modules[\\/]/,
          },
          elementUI: {
            priority: 20,
            name: 'chunk-elementUI',
            test: /[\\/]node_modules[\\/]_?element-ui(.*)/,
          },
          commons: {
            name: 'chunk-commons',
            test: resolve('src/components'), // can customize your rules
            minChunks: 3, // minimum common number
            priority: 5,
            reuseExistingChunk: true,
          },
        },
      })

      config.optimization.runtimeChunk('single')
    })
  },
  configureWebpack: config => {
    const options = {
      externals: {
        BMap: 'BMap',
      },
    }

    if (__PROD__) {
      options.plugins = [
        new CompressionPlugin({
          test: /\.js$|\.css/, // 匹配文件名
          threshold: 10240, // 对超过10K的数据进行压缩
          deleteOriginalAssets: false, // 是否删除原文件
        }),
      ]
    } else {
      options.devtool = 'source-map'
    }

    return options
  },
}
